package main

import (
	"fmt"
	"net"
	"os"
	"time"
)

func main() {
	service := "127.0.0.1:51000"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		handleClient(conn)
	}
}

func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	//for {
	go getMess(conn)
	go sendMess(conn)
	//}
}

func sendMess(conn net.Conn) {
	for {
		var s1 string
		fmt.Scan(&s1)
		fmt.Printf("我说：")
		fmt.Println(s1)
		conn.Write([]byte(s1))
	}
}

func getMess(conn net.Conn) {
	data := make([]byte, 128)
	for {
		read_len, err := conn.Read(data)
		checkError(err)
		if read_len == 0 {
			continue
		}
		fmt.Printf("对面说：")
		fmt.Println(string(data))
		data = make([]byte, 128)
	}
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}
